//
//  XMSSimpleDownLoadManager.m
//  Portal
//
//  Created by JingXing Wu on 12-3-15.
//  Copyright (c) 2012年 GuangZhouXuanWu. All rights reserved.
//

#import "XMSSimpleDownLoadManager.h"

@interface CSimpleDownloadTaskTag()
{
    
}

@property(nonatomic,retain) NSString *URL;
@property(nonatomic,retain) NSString *filePath;
@property(nonatomic,retain) id attachment;

@end

@implementation CSimpleDownloadTaskTag 
{
    NSString *_URL;
    NSString *_filePath;
    id _attachment;
}

@synthesize URL = _URL;
@synthesize filePath = _filePath;
@synthesize attachment = _attachment;

+(CSimpleDownloadTaskTag*)taskTagWithURL:(NSString*)URL filePath:(NSString*)filePath attachment:(id)attachment
{
    CSimpleDownloadTaskTag *tag=[[CSimpleDownloadTaskTag new]autorelease_mm];
    tag.URL = URL;
    tag.filePath = filePath ;
    tag.attachment = attachment;
    return tag;
}

-(void)dealloc
{
    [_URL release_mm];
    [_filePath release_mm];
    [_attachment release_mm];
    superdealloc_mm;
}

@end

static NSString*(^s_transferURL)(NSString *URL);

@interface XMSSimpleDownloadManager() <XMSSimpleDownloadHelperDelegate>
{
    id <XMSSimpleDownloadManagerDelegate> _delegate;
    
    XMSDispatchQueueWrapper *_delegateQueue;
}
@end

@implementation XMSSimpleDownloadManager

- (id)init
{
    self = [super init];
    
    _delegateQueue = [XMSDispatchQueueWrapper new];
    
    return self;
}

- (id)initWithDelegate:(id<XMSSimpleDownloadManagerDelegate>)delegate
{
    self = [self init];
    
    _delegate = delegate;
    
    return self;
}

- (void)dealloc
{
    _delegate = nil;
    [_delegateQueue release_mm];
    superdealloc_mm;
}

- (void)initDownloadQueue:(id <XMSSimpleDownloadManagerDelegate>)delegate
{
    [_delegateQueue dispatchThreadSync:^
    {
        _delegate = delegate;
    }];
}

- (void)simpleDownloadHelperWillStartConnect:(XMSSimpleDownloadHelper*)helper
{
    [_delegateQueue dispatchThreadAsync:^
    {
        if([_delegate respondsToSelector:@selector(simpleDownloadManager:willStartDownload:)])
        {
            CSimpleDownloadTaskTag *tag=[CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
            [_delegate simpleDownloadManager:self willStartDownload:tag];
        }
    }];
}

- (void)simpleDownloadHelperDidStartConnect:(XMSSimpleDownloadHelper *)helper
{
    [_delegateQueue dispatchThreadAsync:^
    {
        if ([_delegate respondsToSelector:@selector(simpleDownloadManager:didStartDownload:)] == YES)
        {
            CSimpleDownloadTaskTag *tag=[CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
            [_delegate simpleDownloadManager:self didStartDownload:tag];
        }
    }];
}

- (void)simpleDownloadHelperFinishLoading:(XMSSimpleDownloadHelper *)helper
{
    CSimpleDownloadTaskTag *tag = [CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
    [_delegateQueue dispatchThreadAsync:^
    {
        [_delegate simpleDownloadManager:self finishedDownload:tag];
    }];
    [CRequestChannelPoolShell removeRequestChannel:^CRequestChannel *
    {
        return helper;
    }];
}

- (void)simpleDownloadHelper:(XMSSimpleDownloadHelper *)helper error:(NSError *)error
{
    [_delegateQueue dispatchThreadAsync:^
    {
        if ([_delegate respondsToSelector:@selector(simpleDownloadManager:tag:error:)] == YES)
        {
            CSimpleDownloadTaskTag *tag=[CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
            [_delegate simpleDownloadManager:self tag:tag error:error];
        }
    }];
    [CRequestChannelPoolShell removeRequestChannel:^CRequestChannel *
    {
        return helper;
    }];
}

- (void)simpleDownloadHelperCancelRequest:(XMSSimpleDownloadHelper *)helper
{
    [_delegateQueue dispatchThreadAsync:^
    {
        if ([_delegate respondsToSelector:@selector(simpleDownloadManager:cancelRequest:)] == YES)
        {
            CSimpleDownloadTaskTag *tag=[CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
            [_delegate simpleDownloadManager:self cancelRequest:tag];
        }
    }];
}

- (void)simpleDownloadHelper:(XMSSimpleDownloadHelper *)helper fileTotalSize:(long long)totalSize
{
    [_delegateQueue dispatchThreadAsync:^
    {
        if ([_delegate respondsToSelector:@selector(simpleDownloadManager:tag:fileTotalSize:)] == YES)
        {
            CSimpleDownloadTaskTag *tag=[CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
            [_delegate simpleDownloadManager:self tag:tag fileTotalSize:totalSize];
        }
    }];
}

- (void)simpleDownloadHelper:(XMSSimpleDownloadHelper *)helper fileTotalSize:(long long)totalSize fileWrittenSize:(long long)writtenSize
{
    [_delegateQueue dispatchThreadAsync:^
    {
        if ([_delegate respondsToSelector:@selector(simpleDownloadManager:tag:fileTotalSize:fileWrittenSize:)] == YES)
        {
            CSimpleDownloadTaskTag *tag=[CSimpleDownloadTaskTag taskTagWithURL:helper.urlString filePath:helper.filePath attachment:helper.attachment];
            [_delegate simpleDownloadManager:self tag:tag fileTotalSize:totalSize fileWrittenSize:writtenSize];
        }
    }];
}

- (NSString*)simpleDownloadHelper:(XMSSimpleDownloadHelper *)helper needTransferURL:(NSString *)URL
{
    if ([_delegate respondsToSelector:@selector(simpleDownloadHelper:needTransferURL:)] == YES)
    {
        NSString *transferURL = [_delegate simpleDownloadManager:self needTransferURL:URL];
        if([transferURL isEqualToString:URL] != YES)
            return transferURL;
        else
        {
            if(s_transferURL != NULL)
                return s_transferURL(URL);
            return URL;
        }
    }
    if(s_transferURL != NULL)
        return s_transferURL(URL);
    
    return URL;
}

- (void)addDownloadTask:(NSString *)szUrl path:(NSString *)szFilepath attachment:(id)attachment
{
    XMSSimpleDownloadHelper *helper = [[[XMSSimpleDownloadHelper alloc] initWithUrl:szUrl path:szFilepath delegate:self] autorelease_mm];
    helper.attachment = attachment;

    [CRequestChannelPoolShell addRequestChannel:^CRequestChannel *
    {
        return helper;
    }];

    NSInvocationOperation *iv = [[[NSInvocationOperation alloc] initWithTarget:helper selector:@selector(startReceiveWaitUntilDone) object:nil] autorelease_mm];
    [super requestInvocationQueuePoolAsyncInvocation:iv];
}

- (void)releaseDownloadQueue
{
    [self terminateAllDownloadTask];
}

- (BOOL)terminateRequest
{
    [self terminateAllDownloadTask];
    return YES;
}

- (void)terminateRequestAsyncComplete:(void (^)(NSInteger))complete
{
    [self terminateRequest];
}

- (void)cancelAllDownloadTask
{
    NSArray* arTask=[self queuePoolTask];
    [super stopRequest];
    for (NSInvocationOperation *iv in arTask)
    {
        XMSSimpleDownloadHelper * nh=(XMSSimpleDownloadHelper *) iv.invocation.target;
        nh.delegate=nil;
        [nh cancelRequest];
        [CRequestChannelPoolShell removeRequestChannel:^CRequestChannel *
        {
            return nh;
        }];
    }
}

- (void)terminateAllDownloadTask
{
    [self cancelAllDownloadTask];
    [_delegateQueue dispatchThreadSync:^
    {
        _delegate = nil;
    }];
}

- (BOOL)isContainDownloadURL:(NSString *)szUrl
{
    for (NSInvocationOperation *iv in [self queuePoolTask])
    {
        if ([((XMSSimpleDownloadHelper *) iv.invocation.target).urlString isEqualToString:szUrl] == YES)
            return YES;
    }
    return NO;
}

//- (void)isContainDownloadFiles:(NSArray *)fileNames cmplete:(void(^)(NSString *fileName,BOOL isExist))complete
//{
//    for(NSString *fileName in fileNames)
//    {
//        BOOL bFind = NO;
//        for (NSInvocationOperation *iv in [self queuePoolTask])
//        {
//            if ([((XMSSimpleDownloadHelper *) iv.invocation.target).urlString rangeOfString:fileName].location != NSNotFound)
//            {
//                bFind = YES;
//            }
//        }
//        complete(fileName,bFind);
//    }
//}

@end


@implementation XMSSimpleDownloadManager (TransferURL)

+(void)operateNeedTransferURLBlock:(NSString *(^)(NSString *))transferURL
{
    if(s_transferURL != NULL)
        Block_release(s_transferURL);
    s_transferURL = NULL;
    if(transferURL != NULL)
        s_transferURL = Block_copy(transferURL);
}

@end